package practise2.util;

import practise2.model.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;

/**
 * Created by Richard on 1/8/2015.
 */
public class CreateTree {
    static public <T> TreeNode<T> createATreeFromArray(List<T> inputArray){
        TreeNode<T> head =null;
        List<TreeNode<T>> nodesQueue = new ArrayList<>();
        if(inputArray!=null){

            for(T value : inputArray){
                if(!nodesQueue.isEmpty()){
                    //for the left node, we add it to its head node directly in the queue
                    if(nodesQueue.get(0).getLeftNode()==null){
                        nodesQueue.get(0).setLeftNode(new TreeNode<T>(value));
                    }
                    else{
                        //for the node, we add at right, we add it at first
                        nodesQueue.get(0).setRightNode(new TreeNode<T>(value));
                        //then remove the full node, and add the both node to the queue
                        TreeNode temp = nodesQueue.get(0);
                        nodesQueue.remove(0);
                        nodesQueue.add(temp.getLeftNode());
                        nodesQueue.add(temp.getRightNode());
                    }
                }else{
                    // this is for the first time when the nodesQueue is empty
                    nodesQueue.add(new TreeNode<T>(value));
                    head = nodesQueue.get(0);
                }

            }
        }

        return head;
    }

    static public <T> void printTreeInLevels(TreeNode<T> treeNode){
        List<TreeNode<T>> nodesQueue = new ArrayList<>();
        if(treeNode!=null){
            nodesQueue.add(treeNode);
            int level =1;
            while (!nodesQueue.isEmpty()){
                int size = nodesQueue.size();
                System.out.println("----level:"+level+"-----");
                while(size>0){

                    TreeNode node = nodesQueue.remove(0);
                    System.out.print("["+node.getValue()+"]");
                    size--;
                    if(node.getLeftNode()!=null){

                        nodesQueue.add(node.getLeftNode());
                    }
                   if(node.getRightNode()!=null){
                       nodesQueue.add(node.getRightNode());
                   }
                }
                level++;
                System.out.println();
            }
        }
    }

    public static void main(String[] args){

        TreeNode node = CreateTree.createATreeFromArray(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8}));
        printTreeInLevels(node);

    }
}
